//
//  BDTabBarViewController.m
//  BadBoy
//
//  Created by wen on 2017/4/14.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDTabBarViewController.h"
#import "BDHomeViewController.h"
#import "BDMessageListViewController.h"
#import "BDMyViewController.h"
#import "BDUserModel.h"
#import "BDApplyFriendsModel.h"
#import "BDFMDBTool.h"
#import "BDLocationServer.h"
#import "BDUserInfoViewController.h"
#import "BDShopMapViewController.h"
#import "BDLoginViewController.h"

static const CGFloat kDefaultPlaySoundInterval = 3.0;
static NSString *kMessageType = @"MessageType";
static NSString *kConversationChatter = @"ConversationChatter";
static NSString *kGroupName = @"GroupName";

@interface BDTabBarViewController ()

@property (strong, nonatomic) NSDate *lastPlaySoundDate;

@end

@implementation BDTabBarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = [UIColor colorWithRed:54/255.0 green:54/255.0 blue:54/255.0 alpha:1.0f];
    view.frame = CGRectMake(0, 0, kBDScreenWidth, kBDTabBarHeight);
//    view.bottom = kBDScreenHeight;
    
    [[UITabBar appearance] insertSubview:view atIndex:0];
    [UITabBar appearance].translucent = NO;
    
    self.view.backgroundColor = [UIColor whiteColor];
    NSArray *classArray = @[[BDHomeViewController class], [BDShopMapViewController class], [BDMessageListViewController class], [BDMyViewController class]];
    NSArray *titleArray = @[ASLocalizedString(@"首页"),ASLocalizedString(@"发现"),ASLocalizedString(@"消息"),ASLocalizedString(@"我的")];
    NSArray *imageArray = @[@"home",@"faxian",@"xinxi",@"wo"];
    [self addChildVCWithClassArray:classArray TitleArray:titleArray ImageArray:imageArray];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"loginOutCurrentUser" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        [((UINavigationController *)self.selectedViewController) popToRootViewControllerAnimated:YES];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"updateUnreadCount" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        [self setupUnreadMessageCount];
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showNotificationWithMessage:) name:@"showNotificationWithMessage" object:nil];
    
//    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"jumpToNewChatVC" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
//        BDUserModel *userModel = x.object;
//        UINavigationController *curNavi = self.selectedViewController;
//        [curNavi popToRootViewControllerAnimated:NO];
//        self.selectedIndex = 2;
//        BDChatViewController *chatController = [[BDChatViewController alloc] initWithConversationChatter:[NSString stringWithFormat:@"%@", @(userModel.user_id)] conversationType:EMConversationTypeChat];
//        chatController.hidesBottomBarWhenPushed = YES;
//        chatController.title = userModel.nickname;
//        [self.selectedViewController pushViewController:chatController animated:YES];
//    }];
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"jumpToNewGroupChat" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
//        BDChatGroupModel *group = x.object;
//        UINavigationController *curNavi = self.selectedViewController;
//        [curNavi popToRootViewControllerAnimated:NO];
//        self.selectedIndex = 2;
//        BDChatViewController *chatController = [[BDChatViewController alloc] initWithConversationChatter:group.groupid conversationType:EMConversationTypeGroupChat];
//        chatController.hidesBottomBarWhenPushed = YES;
//        chatController.title = group.groupname;
//        [self.selectedViewController pushViewController:chatController animated:YES];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"DistrictNotification" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        BDLocationModel * locationModel = [BDLocationModel getLocationInfo];
        NSString *districId = [BDLocationServer getCityIdWithCityName:locationModel.district cityType:BDCityTypeDistrict];
        [self requestDataDistrict:districId];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"jumpToUserInfo" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        NSString *user_id = x.object;
        BDUserInfoViewController *infoViewController = [[BDUserInfoViewController alloc] initWithUserID:user_id.integerValue isFollow:NO guanzhuBlock:nil];
        [self.selectedViewController pushViewController:infoViewController animated:YES];
    }];
    
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"presentToLogin" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
        BDLoginViewController *loginVC = [[BDLoginViewController alloc] init];
        [((UINavigationController *)self.selectedViewController).topViewController presentViewController:[[UINavigationController alloc] initWithRootViewController:loginVC] animated:YES completion:nil];
    }];
}

-(void)requestDataDistrict:(NSString *)distric{
    NSString *url = [NSString stringWithFormat:@"%@user?district_id=%@",KBDBaseURL,distric];
    NSString *headValid = [BDUserModel getHeaderValidation];
    
    RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        // BDLog(ASLocalizedString(@"成功了"));
    }];
}

- (void)refreshSelectedViewController{
    UINavigationController *navi = self.selectedViewController;
    [navi popToRootViewControllerAnimated:YES];
    // BDLog(ASLocalizedString(@"当前控制器类型：%@"), NSStringFromClass([navi.viewControllers.firstObject class]));
    [navi.viewControllers.firstObject loginSuccessRefresh];
}

- (void)addChildVCWithClassArray:(NSArray *)classArray TitleArray:(NSArray *)titleArray ImageArray:(NSArray *)imageArray{
    for (int i = 0; i < titleArray.count; i++) {
        BDBaseViewController *viewController = [[classArray[i] alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:viewController];

        [self addChildViewController:nav];
        
        //设置标题
        nav.tabBarItem.title = titleArray[i];
        [nav.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateSelected];
        //        nav.tabBarItem.badgeValue = value;
        
        //设置普通状态图片
        nav.tabBarItem.image = [UIImage imageNamed:imageArray[i]];
        UIImage *selImg = [UIImage imageNamed:[NSString stringWithFormat:@"%@_sel", imageArray[i]]];
        selImg = [selImg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        nav.tabBarItem.selectedImage = selImg;
    }
//    [ChatDemoHelper shareHelper].mainVC = self;
//    UINavigationController *conListNavi = self.viewControllers[2];
//    [ChatDemoHelper shareHelper].conversationListVC = conListNavi.viewControllers.firstObject;
}

//- (void)networkChanged:(EMConnectionState)connectionState
//{
//    _connectionState = connectionState;
//    UINavigationController *navigation = self.viewControllers[2];
//    BDMessageViewController *messageVC = navigation.viewControllers.firstObject;
//    [messageVC networkChanged:connectionState];
//}

- (void)playSoundAndVibration{
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        // BDLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
        return;
    }
    
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
//    // 收到消息时，播放音频
//    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
//    // 收到消息时，震动
//    [[EMCDDeviceManager sharedInstance] playVibration];
}

- (void)jumpToChatList
{
//    if ([self.navigationController.topViewController isKindOfClass:[BDChatViewController class]]) {
//        //        ChatViewController *chatController = (ChatViewController *)self.navigationController.topViewController;
//        //        [chatController hideImagePicker];
//    }else {
//        [self.navigationController popToViewController:self animated:NO];
//        self.selectedIndex = 2;
//    }
}

// 统计未读消息数
-(void)setupUnreadMessageCount
{
//    UIViewController *messageVC = self.viewControllers[2];
//    if ([EMClient sharedClient].isAutoLogin == NO) {
//        messageVC.tabBarItem.badgeValue = nil;
//        UIApplication *application = [UIApplication sharedApplication];
//        [application setApplicationIconBadgeNumber:0];
//        return;
//    }
//    //1.获取未读消息数量
//    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
//    NSInteger unreadCount = 0;
//    for (EMConversation *conversation in conversations) {
//        unreadCount += conversation.unreadMessagesCount;
//    }
//
//    //2.获取未处理的好友请求数量
//    NSArray *array = [BDFMDBTool queryWithClass:[BDApplyFriendsModel class]];
//    for (BDApplyFriendsModel *appleFriend in array) {
//        if ((appleFriend.applyMode.integerValue == BDApplyFriendModeDefault || appleFriend.applyMode.integerValue == BDApplyFriendModeDelete) && appleFriend.yetToView.integerValue == 0) {
//            unreadCount++;
//        }
//    }
//
//    if (unreadCount > 0) {
//        messageVC.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
//    }else{
//        messageVC.tabBarItem.badgeValue = nil;
//    }
//
//    UIApplication *application = [UIApplication sharedApplication];
//    [application setApplicationIconBadgeNumber:unreadCount];
}

- (void)setupUntreatedApplyCount
{
    //    NSInteger unreadCount = [[[ApplyViewController shareController] dataSource] count];
    //    if (messageVC) {
    //        if (unreadCount > 0) {
    //            messageVC.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
    //        }else{
    //            messageVC.tabBarItem.badgeValue = nil;
    //        }
    //    }
}
//
//- (void)showNotificationWithMessage:(EMMessage *)message{
//    if ([message isKindOfClass:[NSNotification class]]) {
//        NSNotification *notification = (NSNotification *)message;
//        message = notification.object;
//    }
//    NSString *alertBody = nil;
////    if (options.displayStyle == EMPushDisplayStyleMessageSummary) {
//        EMMessageBody *messageBody = message.body;
//        NSString *messageStr = nil;
//        switch (messageBody.type) {
//            case EMMessageBodyTypeText:
//            {
//                messageStr = ((EMTextMessageBody *)messageBody).text;
//            }
//                break;
//            case EMMessageBodyTypeImage:
//            {
//                messageStr = NSLocalizedString(@"message.image", @"Image");
//            }
//                break;
//            case EMMessageBodyTypeLocation:
//            {
//                messageStr = NSLocalizedString(@"message.location", @"Location");
//            }
//                break;
//            case EMMessageBodyTypeVoice:
//            {
//                messageStr = NSLocalizedString(@"message.voice", @"Voice");
//            }
//                break;
//            case EMMessageBodyTypeVideo:{
//                messageStr = NSLocalizedString(@"message.video", @"Video");
//            }
//                break;
//            default:
//                break;
//        }
//
//    BDFridentInfo *friend = [[BDFMDBTool queryWithClass:[BDFridentInfo class] condition:[NSString stringWithFormat:@"user_id = '%@'", message.from]] firstObject];
//
//        do {
//            // BDLog(@"%@",message.from);
//            /*
//             *      title 为发送信息的好友的昵称  这里要自己根据 message.from 来获取到昵称
//             *      暂时用 message.from 来显示
//             */
//
//            NSString *title = friend.nickname;
//            if (message.chatType == EMChatTypeGroupChat) {
//                NSDictionary *ext = message.ext;
//                if (ext && ext[kGroupMessageAtList]) {
//                    id target = ext[kGroupMessageAtList];
//                    if ([target isKindOfClass:[NSString class]]) {
//                        if ([kGroupMessageAtAll compare:target options:NSCaseInsensitiveSearch] == NSOrderedSame) {
//                            alertBody = [NSString stringWithFormat:@"%@%@", title, NSLocalizedString(@"group.atPushTitle", @" @ me in the group")];
//                            break;
//                        }
//                    }
//                    else if ([target isKindOfClass:[NSArray class]]) {
//                        NSArray *atTargets = (NSArray*)target;
//                        if ([atTargets containsObject:[EMClient sharedClient].currentUsername]) {
//                            alertBody = [NSString stringWithFormat:@"%@%@", title, NSLocalizedString(@"group.atPushTitle", @" @ me in the group")];
//                            break;
//                        }
//                    }
//                }
//                NSArray *groupArray = [[EMClient sharedClient].groupManager getJoinedGroups];
//                for (EMGroup *group in groupArray) {
//                    if ([group.groupId isEqualToString:message.conversationId]) {
//                        title = [NSString stringWithFormat:@"%@(%@)", message.from, group.subject];
//                        break;
//                    }
//                }
//            }
//            else if (message.chatType == EMChatTypeChatRoom)
//            {
//                NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
//                NSString *key = [NSString stringWithFormat:@"OnceJoinedChatrooms_%@", [[EMClient sharedClient] currentUsername]];
//                NSMutableDictionary *chatrooms = [NSMutableDictionary dictionaryWithDictionary:[ud objectForKey:key]];
//                NSString *chatroomName = [chatrooms objectForKey:message.conversationId];
//                if (chatroomName)
//                {
//                    title = [NSString stringWithFormat:@"%@(%@)", message.from, chatroomName];
//                }
//            }
//
//            alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
//        } while (0);
////    }
////    else{
////        alertBody = ASLocalizedString(@"您有一条新的消息！");
//////        alertBody = message.body;
////    }
//
//    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];
//    BOOL playSound = NO;
//    if (!self.lastPlaySoundDate || timeInterval >= kDefaultPlaySoundInterval) {
//        self.lastPlaySoundDate = [NSDate date];
//        playSound = YES;
//    }
//
//    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
//    [userInfo setObject:[NSNumber numberWithInt:message.chatType] forKey:kMessageType];
//    [userInfo setObject:message.conversationId forKey:kConversationChatter];
//
//    //发送本地推送
//    if (NSClassFromString(@"UNUserNotificationCenter")) {
//        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.01 repeats:NO];
//        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
//        if (playSound) {
//            content.sound = [UNNotificationSound defaultSound];
//        }
//        content.body =alertBody;
//        content.userInfo = userInfo;
//        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:message.messageId content:content trigger:trigger];
//        [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
//    }
//    else {
//        UILocalNotification *notification = [[UILocalNotification alloc] init];
//        notification.fireDate = [NSDate date]; //触发通知的时间
//        notification.alertBody = alertBody;
//        notification.alertAction = NSLocalizedString(@"open", @"Open");
//        notification.timeZone = [NSTimeZone defaultTimeZone];
//        if (playSound) {
//            notification.soundName = UILocalNotificationDefaultSoundName;
//        }
//        notification.userInfo = userInfo;
//
//        //发送通知
//        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
//    }
//}


//- (EMConversationType)conversationTypeFromMessageType:(EMChatType)type
//{
//    EMConversationType conversatinType = EMConversationTypeChat;
//    switch (type) {
//        case EMChatTypeChat:
//            conversatinType = EMConversationTypeChat;
//            break;
//        case EMChatTypeGroupChat:
//            conversatinType = EMConversationTypeGroupChat;
//            break;
//        case EMChatTypeChatRoom:
//            conversatinType = EMConversationTypeChatRoom;
//            break;
//        default:
//            break;
//    }
//    return conversatinType;
//}

- (UIViewController *)childViewControllerForStatusBarStyle{
    UINavigationController *navi = self.selectedViewController;
    return navi.topViewController;
}

#pragma mark - 自动登录回调

//- (void)willAutoReconnect{
//    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
//    NSNumber *showreconnect = [ud objectForKey:@"identifier_showreconnect_enable"];
//    if (showreconnect && [showreconnect boolValue]) {
//        [self hideHud];
//        [self showHint:NSLocalizedString(@"reconnection.ongoing", @"reconnecting...")];
//    }
//}

//- (void)didAutoReconnectFinishedWithError:(NSError *)error{
//    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
//    NSNumber *showreconnect = [ud objectForKey:@"identifier_showreconnect_enable"];
//    if (showreconnect && [showreconnect boolValue]) {
//        [self hideHud];
//        if (error) {
//            [self showHint:NSLocalizedString(@"reconnection.fail", @"reconnection failure, later will continue to reconnection")];
//        }else{
//            [self showHint:NSLocalizedString(@"reconnection.success", @"reconnection successful！")];
//        }
//    }
//}

//- (void)didReceiveLocalNotification:(UILocalNotification *)notification
//{
//    NSDictionary *userInfo = notification.userInfo;
//    if (userInfo)
//    {
//        if ([self.navigationController.topViewController isKindOfClass:[BDChatViewController class]]) {
//            //            ChatViewController *chatController = (ChatViewController *)self.navigationController.topViewController;
//            //            [chatController hideImagePicker];
//        }
//
//        NSArray *viewControllers = self.navigationController.viewControllers;
//        [viewControllers enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop){
//            if (obj != self)
//            {
//                if (![obj isKindOfClass:[BDChatViewController class]])
//                {
//                    [self.navigationController popViewControllerAnimated:NO];
//                }
//                else
//                {
//                    NSString *conversationChatter = userInfo[kConversationChatter];
//                    BDChatViewController *chatViewController = (BDChatViewController *)obj;
//                    if (![chatViewController.conversation.conversationId isEqualToString:conversationChatter])
//                    {
//                        [self.navigationController popViewControllerAnimated:NO];
//                        EMChatType messageType = [userInfo[kMessageType] intValue];
//#ifdef REDPACKET_AVALABLE
//                        chatViewController = [[RedPacketChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
//#else
//                        chatViewController = [[BDChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
//#endif
//                        [self.navigationController pushViewController:chatViewController animated:NO];
//                    }
//                    *stop= YES;
//                }
//            }
//            else
//            {
//                BDChatViewController *chatViewController = nil;
//                NSString *conversationChatter = userInfo[kConversationChatter];
//                EMChatType messageType = [userInfo[kMessageType] intValue];
//#ifdef REDPACKET_AVALABLE
//                chatViewController = [[RedPacketChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
//#else
//                chatViewController = [[BDChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
//#endif
//                [self.navigationController pushViewController:chatViewController animated:NO];
//            }
//        }];
//    }
//    else {
//        [self.navigationController popToViewController:self animated:NO];
//        self.selectedIndex = 2;
//    }
//}
//
//- (void)didReceiveUserNotification:(UNNotification *)notification
//{
//    NSDictionary *userInfo = notification.request.content.userInfo;
//    if (userInfo)
//    {
//        if ([self.navigationController.topViewController isKindOfClass:[BDChatViewController class]]) {
//            //            ChatViewController *chatController = (ChatViewController *)self.navigationController.topViewController;
//            //            [chatController hideImagePicker];
//        }
//
//        NSArray *viewControllers = self.navigationController.viewControllers;
//        [viewControllers enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop){
//            if (obj != self)
//            {
//                if (![obj isKindOfClass:[BDChatViewController class]])
//                {
//                    [self.navigationController popViewControllerAnimated:NO];
//                }
//                else
//                {
//                    NSString *conversationChatter = userInfo[kConversationChatter];
//                    BDChatViewController *chatViewController = (BDChatViewController *)obj;
//                    if (![chatViewController.conversation.conversationId isEqualToString:conversationChatter])
//                    {
//                        [self.navigationController popViewControllerAnimated:NO];
//                        EMChatType messageType = [userInfo[kMessageType] intValue];
//#ifdef REDPACKET_AVALABLE
//                        chatViewController = [[RedPacketChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
//#else
//                        chatViewController = [[BDChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
//#endif
//                        [self.navigationController pushViewController:chatViewController animated:NO];
//                    }
//                    *stop= YES;
//                }
//            }
//            else
//            {
//                BDChatViewController *chatViewController = nil;
//                NSString *conversationChatter = userInfo[kConversationChatter];
//                EMChatType messageType = [userInfo[kMessageType] intValue];
//#ifdef REDPACKET_AVALABLE
//                chatViewController = [[RedPacketChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
//#else
//                chatViewController = [[BDChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
//#endif
//                [self.navigationController pushViewController:chatViewController animated:NO];
//            }
//        }];
//    }
//    else {
//        [self.navigationController popToViewController:self animated:NO];
//        self.selectedIndex = 2;
//    }
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
